import pandas as pd
import numpy as np
'''
时间格式如下 生成索引列表
'''
date = pd.date_range('20200412', '20201116').to_series()
date = date.dt.month.astype('string').str.zfill(2
       ) +'-'+ date.dt.day.astype('string'
       ).str.zfill(2) +'-'+ '2020'
date = date.tolist()

'''
筛选new york
'''
l = []
for d in date:
    df = pd.read_csv('data/us_report/' + d + '.csv', index_col='Province_State')
    data = df.loc['New York', ['Confirmed','Deaths',
                  'Recovered','Active']]
    l.append(data.to_frame().T)

res = pd.concat(l)
res.index = date

'''
实现join函数
请实现带有 how 参数的 join 函数

假设连接的两表无公共列

调用方式为 join(df1, df2, how="left")

给出测试样例
思路：两个dataframe
1. 选出索引的公共部分intersection
'''
def join(df1, df2, how='left'):
    res_col = df1.columns.tolist() +  df2.columns.tolist()
    dup = df1.index.unique().intersection(df2.index.unique())
    res_df = pd.DataFrame(columns = res_col)
    for label in dup:
        # 合并每行的元素 笛卡尔积
        cartesian = [list(i)+list(j) for i in df1.loc[label
                    ].values.reshape(-1,1) for j in df2.loc[
                      label].values.reshape(-1,1)]
        dup_df = pd.DataFrame(cartesian, index = [label]*len(
                 cartesian), columns = res_col)
        res_df = pd.concat([res_df,dup_df])
        # 左连接找出左边索引右边不包含的index 右侧空出的值填充nan
    if how in ['left', 'outer']:
        for label in df1.index.unique().difference(dup):
            if isinstance(df1.loc[label], pd.DataFrame):
                cat = [list(i)+[np.nan]*df2.shape[1
                      ] for i in df1.loc[label].values]
            else: cat = [list(i)+[np.nan]*df2.shape[1
                      ] for i in df1.loc[label].to_frame().values]
            dup_df = pd.DataFrame(cat, index = [label
                      ]*len(cat), columns = res_col)
            res_df = pd.concat([res_df,dup_df])
    if how in ['right', 'outer']:
        for label in df2.index.unique().difference(dup):
            if isinstance(df2.loc[label], pd.DataFrame):
                cat = [[np.nan]+list(i)*df1.shape[1
                      ] for i in df2.loc[label].values]
            else: cat = [[np.nan]+list(i)*df1.shape[1
                      ] for i in df2.loc[label].to_frame().values]
            dup_df = pd.DataFrame(cat, index = [label
                      ]*len(cat), columns = res_col)
            res_df = pd.concat([res_df,dup_df])
    return res_df
df1 = pd.DataFrame({'col1':[1,2,3,4,5]}, index=list('AABCD'))
df2 = pd.DataFrame({'col2':list('opqrst')}, index=list('ABBCEE'))
join(df1, df2, how='outer')